﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SubSonic;
using ExtAspNet;
using System.Data;


namespace TCMSystem.business.enterprise
{
    public partial class commercial : PageBase
    {
        private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region Module

        /// <summary>
        /// 当前页面所属的模块
        /// </summary>
        public override ModuleType Module
        {
            get
            {
                return ModuleType.BizCommercial;
            }
        }

        #endregion

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            // 权限检查
            CheckPowerDeleteWithButton(btnDeleteSelected);
            CheckPowerNewWithButton(btnNew);
            ResolveDeleteButtonForGrid(btnDeleteSelected, Grid1);
            btnNew.OnClientClick = Window1.GetShowReference("~/business/enterprise/commercial_new.aspx", "新增商贸市场");

            // 每页记录数
            Grid1.PageSize = TblMstConfigHelper.PageSize;

            BindGrid();
        }

        private void BindGrid()
        {
            SqlQuery q = new Select().From<TblBizEnterprise>();
            q.Where("1").IsEqualTo("1");
            // 商贸市场区分：2
            q.And(TblBizEnterprise.EnterpriseTypeColumn).IsEqualTo(2);

            // 在商贸市场名称中搜索
            string searchText = ttbSearchMessage.Text.Trim();
            if (!String.IsNullOrEmpty(searchText))
            {
                q.And(TblBizEnterprise.EnterpriseNameColumn).ContainsString(searchText);
            }

            // 在查询添加之后，排序和分页之前获取总记录数
            // Grid1总共有多少条记录
            Grid1.RecordCount = q.GetRecordCount();

            // 排列
            q.OrderBys.Add(GetSortExpression(Grid1, TblBizEnterprise.Schema));

            // 数据库分页
            q.Paged(Grid1.PageIndex + 1, Grid1.PageSize);
            
            // 判断图片有无
            DataSet ds = q.ExecuteDataSet();

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                if (string.IsNullOrEmpty(ds.Tables[0].Rows[i]["EnterprisePicture"].ToString()))
                {
                    ds.Tables[0].Rows[i]["EnterprisePicture"] = false;
                }
                else
                {
                    ds.Tables[0].Rows[i]["EnterprisePicture"] = true;
                }
            }

            Grid1.DataSource = ds;
            Grid1.DataBind();
        }

        #endregion

        #region Events


        protected void ttbSearchMessage_Trigger2Click(object sender, EventArgs e)
        {
            ttbSearchMessage.ShowTrigger1 = true;
            BindGrid();
        }

        protected void ttbSearchMessage_Trigger1Click(object sender, EventArgs e)
        {
            ttbSearchMessage.Text = String.Empty;
            ttbSearchMessage.ShowTrigger1 = false;
            BindGrid();
        }

        protected void Grid1_PreDataBound(object sender, EventArgs e)
        {
            // 数据绑定之前，进行权限检查
            CheckPowerEditWithWindowField(Grid1, "editField");
            CheckPowerDeleteWithLinkButtonField(Grid1, "deleteField");
            //CheckPowerWithWindowField(ModulePowerType.CoreUser_ChangePassword, Grid1, "changePasswordField");
        }
        

        protected void Grid1_Sort(object sender, GridSortEventArgs e)
        {
            Grid1.SortColumnIndex = e.ColumnIndex;
            BindGrid();
        }

        protected void Grid1_PageIndexChange(object sender, GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }

        protected void btnDeleteSelected_Click(object sender, EventArgs e)
        {
            // 在操作之前进行权限检查
            if (!CheckPowerDelete())
            {
                CheckPowerFailWithAlert();
                return;
            }

            // 从每个选中的行中获取ID（在Grid1中定义的DataKeyNames）
            List<int> ids = GetSelectedDataKeyIDs(Grid1);

            // 执行数据库操作
            new Delete().From<TblBizEnterprise>()
                 .Where(TblBizEnterprise.EnterpriseIdColumn).In(ids)
                 .Execute();

            // 清空当前选中的项
            Grid1.SelectedRowIndexArray = null;

            // 重新绑定表格
            BindGrid();
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            int id = Convert.ToInt32(Grid1.DataKeys[e.RowIndex][0]);

            if (e.CommandName == "Delete")
            {
                // 在操作之前进行权限检查
                if (!CheckPowerDelete())
                {
                    CheckPowerFailWithAlert();
                    return;
                }

                //TODO:图片应该同时删除，否则产生垃圾数据和文件
                TblBizEnterprise.Delete(id);

                BindGrid();
            }

        }

        protected void Window1_Close(object sender, EventArgs e)
        {
            BindGrid();
        }

        protected void rblEnableStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindGrid();
        }


        #endregion

    }
}
